<template>
  <div class="user-manage-container">
    <el-card class="header">
      <div class="header-content">
            <div class="search">
                <span>用户名搜索</span>
                <el-input v-model="nameSearch" class="input"></el-input>
                <el-button @click="handleSearch" type="primary">搜索</el-button>
            </div>
             <el-button type="primary"  @click="onAddUser">{{ $t('msg.excel.addUser') }}</el-button>
        </div>
      <div>
      </div>
    </el-card>
    <el-card>
      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <!-- 序列号 -->
        <el-table-column label="#" type="index" align="center" />
        <!-- 用户名 -->
        <el-table-column :label="$t('msg.excel.username')" prop="username" align="center"/>
        <!-- 联系方式 -->
        <el-table-column :label="$t('msg.excel.mobile')" prop="phone" align="center" />
        <!-- 头像 -->
        <!-- <el-table-column :label="$t('msg.excel.avatar')" align="center">
          <template #default="{ row }">
            <el-image
              class="avatar"
              :src="row.avatar"
              :preview-src-list="[row.avatar]"
            />
          </template>
        </el-table-column> -->
         <!-- 本人姓名 -->
         <el-table-column :label="$t('msg.excel.name')" prop="fullname" align="center" />
        <!-- 性别 -->
        <el-table-column :label="$t('msg.excel.sex')" align="center">
          <template #default="{ row }">
              <el-tag size="mini" :type="row.sex == 'woman' ? 'danger': ''">{{ row.sex == 'woman' ? '女': '男' }}</el-tag>
          </template>
        </el-table-column>
        <!-- 开通时间 -->
        <el-table-column :label="$t('msg.excel.openTime')" align="center">
          <template #default="{ row }">
            {{ getData(row.registrationTime) }}
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column
          :label="$t('msg.excel.action')"
          fixed="right"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            <el-button type="primary" size="mini" @click="onShowUser(row)">{{
              $t('msg.excel.show')
            }}</el-button>
            <el-button type="danger" size="mini" @click="onDeleteUser(row)" v-if="store.getters.userInfo.role != '员工'">{{
              $t('msg.excel.remove')
            }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="page"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="size"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
  <Dialog
    v-if="dialogFormVisible"
    :dialogVisible = dialogFormVisible
    :type = dialogType
    :userFormInitial="userFormInitial"
    @dialogShow="dialogShow"
    @Confirm="handleConfirm"
  />
</template>

<script setup>
import { onMounted, ref, onActivated } from 'vue'
import {getUsersInfo,deleteUser,registerUser} from '@/api/user-manage'
import { watchSwitchLang } from '@/utils/i18n'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { useStore } from 'vuex'
import dayjs from 'dayjs'
import Dialog from './components/Dialog.vue'
// 存储表格数据
const tableData = ref([])
const total = ref(0)
const page = ref(1)
const size = ref(5)
const router = useRouter()
const i18n = useI18n()
const dialogFormVisible = ref(false)
const dialogType = ref('')
const userFormInitial = ref()
let loading = ref(false)
// 名称搜索
const nameSearch = ref('')
const store = useStore()
// 调用接口,获取表格数据
const getUserList = async () => {
  loading.value = true
  const result = await getUsersInfo({
    page: page.value,
    pageSize: size.value
  })
  tableData.value = result.findData
  loading.value = false
  // total.value = result.total
}
// page-size改变时触发
const handleSizeChange = (currentSize) => {
  size.value = currentSize
  getUserList()
}
// current-page 改变时触发
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  getUserList()
}
// 对时间戳样式进行转换
const getData = (n) =>{
  return dayjs(n).format('YYYY-MM-DD HH:mm:ss')
}
//   点击搜索时的回调函数
const handleSearch = async() =>{
  page.value = 1
     // 调用模糊搜索的接口
  const query = {
    username:nameSearch.value,
    page:page.value,
    pageSize:size.value
  }
  const data = await getUsersInfo(query)
  tableData.value = data.findData
  total.value = data.findData.length
  // 修改分页器总数的显示，当输入框中搜索东西的时候，再这样修改
  if(nameSearch.value !== ''){
    total.value = data.findData.length
  }else{
    // 没有输入东西的时候，通过接口获取全部数据，再进行赋值
    const getData = await getUsersInfo()
    total.value = getData.findData.length
  }
  nameSearch.value = ''
}
// 添加用户操作
const onAddUser = () =>{
  dialogFormVisible.value = true
  dialogType.value = 'add'
}
// 展示用户信息
const onShowUser = (row) =>{
  dialogFormVisible.value = true
  userFormInitial.value = row
  dialogType.value = 'show'
}
// 弹框关闭时
const dialogShow =(isShow) =>{
  dialogFormVisible.value = isShow
}
// 子组件点击确定时的回调函数
const handleConfirm = async (value,type) =>{
  loading.value = true
    const userInfo = {
        ...value,
        age:Number(value.age),
    }
    // 调用创建用户接口
    await registerUser(userInfo)
    ElMessage({
      type: 'success',
      message: i18n.t('msg.excel.addSuccess')
    })
    // 重新获取用户信息
    getUserList()
    // 获取全部的数据，返回给total
    const getData = await getUsersInfo()
    total.value = getData.findData.length
    loading.value = false
}
// 删除操作
const onDeleteUser = (row) => {
  ElMessageBox.confirm(
    i18n.t('msg.excel.dialogTitle1') +
      row.username +
      i18n.t('msg.excel.dialogTitle2'),
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    await deleteUser({id:row._id})
    ElMessage({
      type: 'success',
      message: i18n.t('msg.excel.removeSuccess')
    })
    getUserList()
  })
}
// 监听语言切换
watchSwitchLang(getUserList)
/**
 *  调用时机为首次挂载
 *  以及每次从缓存中被重新插入时
 * 处理导入用户后数据不重新加载的问题
 */
onActivated(getUserList)
onMounted(async() => {
  getUserList()
  // 获取全部的数据，返回给total
  const getData = await getUsersInfo()
  total.value = getData.findData.length
})
</script>

<style lang="scss" scoped>
.user-manage-container {
  .header {
      margin-bottom: 22px;
      text-align: right;
      .header-content{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .search{
            display: flex;
            align-items: center;
            width: 50%;
            .input{
                width: 30%;
                margin: 0 10px;
            }
        }
      }
    }
  :deep(.el-image) {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  :deep(.el-tag) {
    margin-right: 6px;
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
